package com.code.productorAndCustomer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DemoLock {

    public static void main(String[] args) {
        Data2 data = new Data2();

        new Thread(()->{
            for(int i = 0; i < 10; i++) {
                try {
                    data.productGood();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"生产者A").start();

        new Thread(()->{
            for(int i = 0; i < 10; i++) {
                try {
                    data.customGood();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"消费者B").start();

        new Thread(()->{
            for(int i = 0; i < 10; i++) {
                try {
                    data.productGood();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"生产者C").start();

        new Thread(()->{
            for(int i = 0; i < 10; i++) {
                try {
                    data.customGood();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"消费者D").start();
    }
}

//数据
class Data2{
    private int goods;

    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void productGood() throws InterruptedException {
        lock.lock();
        while(goods != 0){
            //有商品，生产者等待
            condition.await();
        }
        goods++;
        System.out.println(Thread.currentThread().getName()+"---生产--"+goods);
        //通知其他线程我生产了
        condition.signalAll();
        lock.unlock();
    }

    public void customGood() throws InterruptedException {
        lock.lock();
        while (goods == 0){
            //没有商品消费者等待
            condition.await();
        }
        goods--;
        System.out.println(Thread.currentThread().getName()+"---消费--"+goods);
        //呼叫其他线程，我消费了，该生产了
        condition.signalAll();
        lock.unlock();
    }

}



